<template>
  <div class="task-page">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-circle circle-1"></div>
      <div class="decoration-circle circle-2"></div>
      <div class="decoration-circle circle-3"></div>
    </div>

    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">
        <span class="title-icon">🎯</span>
        智能学习任务
      </h1>
      <p class="page-subtitle">
        基于科学学习理论，帮你设定目标、养成习惯、持续进步
      </p>

      <!-- 学习动机卡片 -->
      <div class="motivation-card">
        <div class="motivation-content">
          <div class="motivation-icon">💪</div>
          <div class="motivation-text">
            <h3>{{ getMotivationMessage() }}</h3>
            <p>{{ getMotivationSubtext() }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="page-container">
      <!-- 今日任务列表 -->
      <div class="glass-card tasks-section">
        <div class="section-header">
          <h2 class="card-title">
            <span class="title-icon">📋</span>
            今日任务
          </h2>
          <button class="add-task-btn" @click="showAddTaskModal = true">
            <span class="btn-icon">➕</span>
            添加任务
          </button>
        </div>

        <div class="tasks-list">
          <div
            v-for="task in todayTasks"
            :key="task.id"
            class="task-item"
            :class="{ completed: task.completed }"
          >
            <div class="task-checkbox">
              <input
                v-model="task.completed"
                type="checkbox"
                class="task-checkbox-input"
                @change="updateTaskStatus(task)"
              />
            </div>
            <div class="task-content">
              <h4 class="task-title">{{ task.title }}</h4>
              <p class="task-description">{{ task.description }}</p>
              <div class="task-meta">
                <span class="task-type">{{ task.type }}</span>
                <span class="task-duration"
                  >预计 {{ task.estimatedTime }} 分钟</span
                >
                <span
                  class="task-priority"
                  :class="'priority-' + task.priority"
                >
                  {{ getPriorityText(task.priority) }}
                </span>
              </div>
            </div>
            <div class="task-actions">
              <button class="task-action-btn edit-btn" @click="editTask(task)">
                <span class="btn-icon">✏️</span>
              </button>
              <button
                class="task-action-btn delete-btn"
                @click="deleteTask(task.id)"
              >
                <span class="btn-icon">🗑️</span>
              </button>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="todayTasks.length === 0" class="empty-tasks">
            <div class="empty-icon">📝</div>
            <h3>暂无今日任务</h3>
            <p>点击"添加任务"开始规划你的学习计划</p>
          </div>
        </div>
      </div>

      <!-- 智能目标设定 -->
      <div class="glass-card goals-section">
        <h2 class="card-title">
          <span class="title-icon">🎯</span>
          智能目标设定
        </h2>

        <div class="goals-container">
          <div class="goal-setting-card">
            <h3>今日学习目标</h3>
            <div class="goal-input-group">
              <input
                v-model="dailyGoal.time"
                type="number"
                class="goal-input"
                placeholder="30"
                min="5"
                max="180"
              />
              <span class="goal-unit">分钟</span>
            </div>
            <div class="goal-input-group">
              <input
                v-model="dailyGoal.tasks"
                type="number"
                class="goal-input"
                placeholder="3"
                min="1"
                max="10"
              />
              <span class="goal-unit">个任务</span>
            </div>
            <button class="set-goal-btn" @click="setDailyGoal">设定目标</button>
          </div>

          <div class="goal-progress-card">
            <h3>目标完成情况</h3>
            <div class="progress-circle">
              <div
                class="progress-ring"
                :style="{ '--progress': goalProgress + '%' }"
              >
                <span class="progress-text">{{ goalProgress }}%</span>
              </div>
            </div>
            <div class="goal-stats">
              <div class="stat-item">
                <span class="stat-label">学习时长</span>
                <span class="stat-value">{{ todayStats.studyTime }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">完成任务</span>
                <span class="stat-value"
                  >{{ todayStats.completedTasks }}/{{ dailyGoal.tasks }}</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 今日学习概览 -->
      <div class="glass-card overview-section">
        <h2 class="card-title">
          <span class="title-icon">📊</span>
          今日学习概览
        </h2>

        <div class="stats-grid">
          <div class="stat-card" @click="showDetailModal('time')">
            <div class="stat-icon">⏰</div>
            <div class="stat-content">
              <div class="stat-value">{{ todayStats.studyTime }}</div>
              <div class="stat-label">学习时长</div>
              <div class="stat-trend" :class="getTrendClass('time')">
                {{ getTrendText("time") }}
              </div>
            </div>
          </div>
          <div class="stat-card" @click="showDetailModal('tasks')">
            <div class="stat-icon">✅</div>
            <div class="stat-content">
              <div class="stat-value">{{ todayStats.completedTasks }}</div>
              <div class="stat-label">完成任务</div>
              <div class="stat-trend" :class="getTrendClass('tasks')">
                {{ getTrendText("tasks") }}
              </div>
            </div>
          </div>
          <div class="stat-card" @click="showDetailModal('questions')">
            <div class="stat-icon">📚</div>
            <div class="stat-content">
              <div class="stat-value">{{ todayStats.questionsAnswered }}</div>
              <div class="stat-label">答题数量</div>
              <div class="stat-trend" :class="getTrendClass('questions')">
                {{ getTrendText("questions") }}
              </div>
            </div>
          </div>
          <div class="stat-card" @click="showDetailModal('streak')">
            <div class="stat-icon">🔥</div>
            <div class="stat-content">
              <div class="stat-value">{{ todayStats.streakDays }}</div>
              <div class="stat-label">连续天数</div>
              <div class="stat-trend" :class="getTrendClass('streak')">
                {{ getTrendText("streak") }}
              </div>
            </div>
          </div>
        </div>

        <!-- 今日进度 -->
        <div class="progress-section">
          <h3 class="progress-title">今日目标进度</h3>
          <div class="progress-bar-container">
            <div class="progress-bar">
              <div
                class="progress-fill"
                :style="{ width: todayProgress + '%' }"
              ></div>
            </div>
            <div class="progress-text">{{ todayProgress }}%</div>
          </div>
          <div class="progress-tips">
            <span v-if="todayProgress < 30" class="tip-text"
              >💡 建议设定更小的目标，从微习惯开始</span
            >
            <span v-else-if="todayProgress < 70" class="tip-text"
              >👍 进度不错，继续保持！</span
            >
            <span v-else-if="todayProgress < 100" class="tip-text"
              >🚀 接近目标了，再加把劲！</span
            >
            <span v-else class="tip-text"
              >🎉 目标完成！明天可以挑战更高目标</span
            >
          </div>
        </div>
      </div>

      <!-- 科学学习功能 -->
      <div class="glass-card science-learning-section">
        <h2 class="card-title">
          <span class="title-icon">🧠</span>
          科学学习功能
        </h2>

        <div class="science-features">
          <div class="feature-card">
            <div class="feature-icon">🔄</div>
            <div class="feature-content">
              <h4>间隔重复复习</h4>
              <p>基于遗忘曲线，智能安排复习时间</p>
              <div class="review-schedule">
                <div
                  class="schedule-item"
                  v-for="item in reviewSchedule"
                  :key="item.id"
                >
                  <span class="schedule-time">{{ item.time }}</span>
                  <span class="schedule-content">{{ item.content }}</span>
                  <span class="schedule-status" :class="item.status">{{
                    item.statusText
                  }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="feature-card">
            <div class="feature-icon">🎯</div>
            <div class="feature-content">
              <h4>检索练习</h4>
              <p>主动回忆训练，提高记忆保持</p>
              <div class="retrieval-stats">
                <div class="retrieval-item">
                  <span class="retrieval-label">今日练习</span>
                  <span class="retrieval-value">{{
                    retrievalStats.today
                  }}</span>
                </div>
                <div class="retrieval-item">
                  <span class="retrieval-label">成功率</span>
                  <span class="retrieval-value"
                    >{{ retrievalStats.successRate }}%</span
                  >
                </div>
              </div>
            </div>
          </div>

          <div class="feature-card">
            <div class="feature-icon">🤔</div>
            <div class="feature-content">
              <h4>元认知监控</h4>
              <p>评估学习效果，调整学习策略</p>
              <div class="metacognition-chart">
                <div class="confidence-level">
                  <span class="confidence-label">学习信心</span>
                  <div class="confidence-bar">
                    <div
                      class="confidence-fill"
                      :style="{ width: metacognitionData.confidence + '%' }"
                    ></div>
                  </div>
                  <span class="confidence-value"
                    >{{ metacognitionData.confidence }}%</span
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 学习习惯分析 -->
      <div class="glass-card habits-section">
        <h2 class="card-title">
          <span class="title-icon">📈</span>
          学习习惯分析
        </h2>

        <div class="habits-grid">
          <div class="habit-item">
            <div class="habit-icon">📅</div>
            <div class="habit-content">
              <h4 class="habit-title">学习频率</h4>
              <p class="habit-desc">
                最近7天学习 {{ weeklyStats.studyDays }} 天
              </p>
              <div class="habit-progress">
                <div class="progress-bar">
                  <div
                    class="progress-fill"
                    :style="{ width: (weeklyStats.studyDays / 7) * 100 + '%' }"
                  ></div>
                </div>
              </div>
            </div>
          </div>

          <div class="habit-item">
            <div class="habit-icon">⏱️</div>
            <div class="habit-content">
              <h4 class="habit-title">平均学习时长</h4>
              <p class="habit-desc">
                每日平均 {{ weeklyStats.avgStudyTime }} 分钟
              </p>
              <div class="habit-progress">
                <div class="progress-bar">
                  <div
                    class="progress-fill"
                    :style="{
                      width:
                        Math.min((weeklyStats.avgStudyTime / 60) * 100, 100) +
                        '%',
                    }"
                  ></div>
                </div>
              </div>
            </div>
          </div>

          <div class="habit-item">
            <div class="habit-icon">🎯</div>
            <div class="habit-content">
              <h4 class="habit-title">目标完成率</h4>
              <p class="habit-desc">
                最近7天完成率 {{ weeklyStats.completionRate }}%
              </p>
              <div class="habit-progress">
                <div class="progress-bar">
                  <div
                    class="progress-fill"
                    :style="{ width: weeklyStats.completionRate + '%' }"
                  ></div>
                </div>
              </div>
            </div>
          </div>

          <div class="habit-item">
            <div class="habit-icon">🏆</div>
            <div class="habit-content">
              <h4 class="habit-title">学习成就</h4>
              <p class="habit-desc">{{ getAchievementText() }}</p>
              <div class="achievement-badges">
                <span v-if="weeklyStats.streakDays >= 7" class="badge"
                  >🔥 连续学习</span
                >
                <span v-if="weeklyStats.avgStudyTime >= 60" class="badge"
                  >⏰ 学习达人</span
                >
                <span v-if="weeklyStats.completionRate >= 80" class="badge"
                  >🎯 目标达成</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 学习建议 -->
      <div class="glass-card suggestions-section">
        <h2 class="card-title">
          <span class="title-icon">💡</span>
          学习建议
        </h2>

        <div class="suggestions-list">
          <div
            v-for="suggestion in learningSuggestions"
            :key="suggestion.id"
            class="suggestion-item"
            :class="'suggestion-' + suggestion.type"
          >
            <div class="suggestion-icon">{{ suggestion.icon }}</div>
            <div class="suggestion-content">
              <h4 class="suggestion-title">{{ suggestion.title }}</h4>
              <p class="suggestion-desc">{{ suggestion.description }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加任务模态框 -->
    <div
      v-if="showAddTaskModal"
      class="modal-overlay"
      @click="closeAddTaskModal"
    >
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">添加学习任务</h3>
          <button class="modal-close" @click="closeAddTaskModal">×</button>
        </div>

        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">任务标题</label>
            <input
              v-model="newTask.title"
              type="text"
              class="form-input"
              placeholder="输入任务标题"
            />
          </div>

          <div class="form-group">
            <label class="form-label">任务描述</label>
            <textarea
              v-model="newTask.description"
              class="form-textarea"
              placeholder="输入任务描述"
              rows="3"
            ></textarea>
          </div>

          <div class="form-group">
            <label class="form-label">任务类型</label>
            <select v-model="newTask.type" class="form-select">
              <option value="reading">阅读学习</option>
              <option value="practice">练习答题</option>
              <option value="review">复习回顾</option>
              <option value="exam">模拟考试</option>
            </select>
          </div>

          <div class="form-group">
            <label class="form-label">预计时长（分钟）</label>
            <input
              v-model="newTask.estimatedTime"
              type="number"
              class="form-input"
              min="5"
              max="180"
            />
          </div>

          <div class="form-group">
            <label class="form-label">优先级</label>
            <select v-model="newTask.priority" class="form-select">
              <option value="low">低</option>
              <option value="medium">中</option>
              <option value="high">高</option>
            </select>
          </div>
        </div>

        <div class="modal-footer">
          <button class="secondary-btn" @click="closeAddTaskModal">取消</button>
          <button class="primary-btn" @click="addTask">添加任务</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getUserStudyStats,
  getTodayTasks,
  createTask,
  updateTaskStatus,
  deleteTask,
  getLearningHabits,
  getLearningSuggestions,
  recordStudyTime,
} from "@/api/task";

export default {
  name: "TaskPage",
  data() {
    return {
      // 今日统计数据
      todayStats: {
        studyTime: "45分钟",
        completedTasks: 3,
        questionsAnswered: 25,
        streakDays: 7,
      },

      // 每日目标设定
      dailyGoal: {
        time: 30,
        tasks: 3,
      },

      // 复习计划（基于间隔重复理论）
      reviewSchedule: [
        {
          id: 1,
          time: "09:00",
          content: "复习Vue.js基础概念",
          status: "pending",
          statusText: "待复习",
        },
        {
          id: 2,
          time: "14:00",
          content: "JavaScript闭包练习",
          status: "completed",
          statusText: "已完成",
        },
        {
          id: 3,
          time: "19:00",
          content: "算法题回顾",
          status: "pending",
          statusText: "待复习",
        },
      ],

      // 检索练习统计
      retrievalStats: {
        today: 15,
        successRate: 87,
      },

      // 元认知数据
      metacognitionData: {
        confidence: 75,
        difficulty: "medium",
        focus: "good",
      },

      // 今日任务列表
      todayTasks: [
        {
          id: 1,
          title: "完成Vue.js基础练习",
          description: "完成20道Vue.js基础概念题目",
          type: "practice",
          estimatedTime: 30,
          priority: "high",
          completed: false,
        },
        {
          id: 2,
          title: "复习JavaScript闭包",
          description: "阅读相关文章并做笔记",
          type: "reading",
          estimatedTime: 20,
          priority: "medium",
          completed: true,
        },
        {
          id: 3,
          title: "算法题练习",
          description: "完成5道数组相关算法题",
          type: "practice",
          estimatedTime: 45,
          priority: "medium",
          completed: false,
        },
      ],

      // 周统计数据
      weeklyStats: {
        studyDays: 5,
        avgStudyTime: 45,
        completionRate: 75,
        streakDays: 7,
      },

      // 学习建议
      learningSuggestions: [
        {
          id: 1,
          type: "tip",
          icon: "💡",
          title: "学习时间建议",
          description:
            "建议将学习时间安排在上午9-11点或下午2-4点，这些时间段大脑最为活跃。",
        },
        {
          id: 2,
          type: "warning",
          icon: "⚠️",
          title: "注意休息",
          description: "连续学习超过45分钟建议休息10-15分钟，保护眼睛和大脑。",
        },
        {
          id: 3,
          type: "success",
          icon: "🎉",
          title: "学习成就",
          description: "恭喜！你已经连续学习7天，继续保持这个好习惯！",
        },
      ],

      // 模态框状态
      showAddTaskModal: false,
      showDetailModalVisible: false,
      detailModalType: "",

      // 历史数据对比（用于趋势分析）
      yesterdayStats: {
        studyTime: "35分钟",
        completedTasks: 2,
        questionsAnswered: 20,
        streakDays: 6,
      },

      // 新任务表单
      newTask: {
        title: "",
        description: "",
        type: "practice",
        estimatedTime: 30,
        priority: "medium",
      },
    };
  },

  computed: {
    // 今日进度计算
    todayProgress() {
      const completedTasks = this.todayTasks.filter(
        (task) => task.completed
      ).length;
      const totalTasks = this.todayTasks.length;
      return totalTasks > 0
        ? Math.round((completedTasks / totalTasks) * 100)
        : 0;
    },

    // 目标完成进度
    goalProgress() {
      const timeProgress = Math.min(
        (parseInt(this.todayStats.studyTime) / this.dailyGoal.time) * 100,
        100
      );
      const taskProgress = Math.min(
        (this.todayStats.completedTasks / this.dailyGoal.tasks) * 100,
        100
      );
      return Math.round((timeProgress + taskProgress) / 2);
    },
  },

  mounted() {
    this.init();
  },

  methods: {
    // 初始化页面数据
    async init() {
      try {
        await Promise.all([
          this.loadUserData(),
          this.loadTasks(),
          this.loadLearningHabits(),
          this.loadLearningSuggestions(),
        ]);
      } catch (error) {
        console.error("初始化失败:", error);
        this.$message.error("数据加载失败，请稍后重试");
      }
    },

    // 加载用户数据
    async loadUserData() {
      try {
        const response = await getUserStudyStats();
        if (response && response.data) {
          this.todayStats = {
            studyTime: response.data.todayStudyTime || "0分钟",
            completedTasks: response.data.completedTasks || 0,
            questionsAnswered: response.data.questionsAnswered || 0,
            streakDays: response.data.streakDays || 0,
          };
          this.weeklyStats = {
            studyDays: response.data.weeklyStudyDays || 0,
            avgStudyTime: response.data.avgStudyTime || 0,
            completionRate: response.data.completionRate || 0,
            streakDays: response.data.streakDays || 0,
          };
        }
      } catch (error) {
        console.error("加载用户数据失败:", error);
        // 使用默认数据
      }
    },

    // 加载任务列表
    async loadTasks() {
      try {
        const response = await getTodayTasks();
        if (response && response.data) {
          this.todayTasks = response.data;
        } else {
          // 从本地存储加载
          const savedTasks = localStorage.getItem("todayTasks");
          if (savedTasks) {
            this.todayTasks = JSON.parse(savedTasks);
          }
        }
      } catch (error) {
        console.error("加载任务列表失败:", error);
        // 从本地存储加载
        const savedTasks = localStorage.getItem("todayTasks");
        if (savedTasks) {
          this.todayTasks = JSON.parse(savedTasks);
        }
      }
    },

    // 保存任务列表
    saveTasks() {
      localStorage.setItem("todayTasks", JSON.stringify(this.todayTasks));
    },

    // 更新任务状态
    async updateTaskStatus(task) {
      try {
        await updateTaskStatus(task.id, task.completed);
        this.saveTasks();
        if (task.completed) {
          this.$message.success(`任务"${task.title}"已完成！`);
          // 更新统计数据
          this.todayStats.completedTasks++;
        } else {
          this.todayStats.completedTasks--;
        }
      } catch (error) {
        console.error("更新任务状态失败:", error);
        // 回滚状态
        task.completed = !task.completed;
        this.$message.error("更新任务状态失败，请重试");
      }
    },

    // 添加任务
    async addTask() {
      if (!this.newTask.title.trim()) {
        this.$message.warning("请输入任务标题");
        return;
      }

      const taskData = {
        title: this.newTask.title,
        description: this.newTask.description,
        type: this.newTask.type,
        estimatedTime: this.newTask.estimatedTime,
        priority: this.newTask.priority,
        completed: false,
      };

      try {
        const response = await createTask(taskData);
        if (response && response.data) {
          this.todayTasks.push(response.data);
        } else {
          // 如果API失败，使用本地ID
          const task = {
            id: Date.now(),
            ...taskData,
          };
          this.todayTasks.push(task);
        }

        this.saveTasks();
        this.closeAddTaskModal();
        this.$message.success("任务添加成功！");
      } catch (error) {
        console.error("添加任务失败:", error);
        // 使用本地存储
        const task = {
          id: Date.now(),
          ...taskData,
        };
        this.todayTasks.push(task);
        this.saveTasks();
        this.closeAddTaskModal();
        this.$message.success("任务添加成功（本地保存）！");
      }
    },

    // 编辑任务
    editTask(task) {
      // 这里可以实现编辑功能
      console.log("编辑任务:", task.title);
      this.$message.info("编辑功能开发中...");
    },

    // 删除任务
    deleteTask(taskId) {
      this.$confirm("确定要删除这个任务吗？", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await deleteTask(taskId);
            this.todayTasks = this.todayTasks.filter(
              (task) => task.id !== taskId
            );
            this.saveTasks();
            this.$message.success("任务已删除");
          } catch (error) {
            console.error("删除任务失败:", error);
            // 仍然从本地删除
            this.todayTasks = this.todayTasks.filter(
              (task) => task.id !== taskId
            );
            this.saveTasks();
            this.$message.success("任务已删除（本地）");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 关闭添加任务模态框
    closeAddTaskModal() {
      this.showAddTaskModal = false;
      this.newTask = {
        title: "",
        description: "",
        type: "practice",
        estimatedTime: 30,
        priority: "medium",
      };
    },

    // 获取优先级文本
    getPriorityText(priority) {
      const priorityMap = {
        low: "低",
        medium: "中",
        high: "高",
      };
      return priorityMap[priority] || "中";
    },

    // 获取成就文本
    getAchievementText() {
      if (this.weeklyStats.streakDays >= 30) {
        return "学习大师！连续学习30天以上";
      } else if (this.weeklyStats.streakDays >= 7) {
        return "学习达人！连续学习一周以上";
      } else if (this.weeklyStats.streakDays >= 3) {
        return "学习新手！继续保持";
      } else {
        return "开始你的学习之旅吧！";
      }
    },

    // 加载学习习惯分析
    async loadLearningHabits() {
      try {
        const response = await getLearningHabits();
        if (response && response.data) {
          this.weeklyStats = { ...this.weeklyStats, ...response.data };
        }
      } catch (error) {
        console.error("加载学习习惯失败:", error);
      }
    },

    // 加载学习建议
    async loadLearningSuggestions() {
      try {
        const response = await getLearningSuggestions();
        if (response && response.data) {
          this.learningSuggestions = response.data;
        }
      } catch (error) {
        console.error("加载学习建议失败:", error);
      }
    },

    // 记录学习时长
    async recordStudyTime(duration) {
      try {
        await recordStudyTime(duration);
        // 更新本地统计数据
        const currentTime = parseInt(this.todayStats.studyTime) || 0;
        this.todayStats.studyTime = currentTime + duration + "分钟";
      } catch (error) {
        console.error("记录学习时长失败:", error);
      }
    },

    // 设定每日目标（基于目标设定理论）
    setDailyGoal() {
      if (!this.dailyGoal.time || !this.dailyGoal.tasks) {
        this.$message.warning("请设定完整的学习目标");
        return;
      }

      // 保存目标到本地存储
      localStorage.setItem("dailyGoal", JSON.stringify(this.dailyGoal));

      // 生成个性化建议
      const suggestions = this.generateGoalSuggestions();
      this.$message.success(`目标设定成功！${suggestions}`);

      // 更新学习建议
      this.updateLearningSuggestions();
    },

    // 生成目标建议
    generateGoalSuggestions() {
      const time = this.dailyGoal.time;
      const tasks = this.dailyGoal.tasks;

      if (time <= 30 && tasks <= 3) {
        return "建议从微习惯开始，循序渐进！";
      } else if (time <= 60 && tasks <= 5) {
        return "目标适中，保持专注和坚持！";
      } else {
        return "目标较高，记得合理安排休息时间！";
      }
    },

    // 获取动机信息（基于自我决定理论）
    getMotivationMessage() {
      const hour = new Date().getHours();

      if (hour < 12) {
        return "早上好！新的一天，新的学习机会！";
      } else if (hour < 18) {
        return "下午时光，继续你的学习之旅！";
      } else {
        return "晚上好！回顾今天的学习成果！";
      }
    },

    getMotivationSubtext() {
      const streak = this.todayStats.streakDays;
      if (streak >= 7) {
        return `你已经连续学习${streak}天，太棒了！继续保持这个好习惯！`;
      } else if (streak >= 3) {
        return `连续学习${streak}天，正在养成良好习惯！`;
      } else {
        return "开始你的学习之旅，每天进步一点点！";
      }
    },

    // 更新学习建议（基于元认知理论）
    updateLearningSuggestions() {
      const progress = this.goalProgress;
      const confidence = this.metacognitionData.confidence;

      this.learningSuggestions = [
        {
          id: 1,
          type: "tip",
          icon: "💡",
          title: "学习时间建议",
          description:
            "建议将学习时间安排在上午9-11点或下午2-4点，这些时间段大脑最为活跃。",
        },
        {
          id: 2,
          type: "warning",
          icon: "⚠️",
          title: "注意休息",
          description: "连续学习超过45分钟建议休息10-15分钟，保护眼睛和大脑。",
        },
        {
          id: 3,
          type: "success",
          icon: "🎉",
          title: "学习成就",
          description: `恭喜！你已经连续学习${this.todayStats.streakDays}天，继续保持这个好习惯！`,
        },
      ];

      // 根据进度和信心添加个性化建议
      if (progress < 50) {
        this.learningSuggestions.push({
          id: 4,
          type: "tip",
          icon: "🎯",
          title: "目标调整建议",
          description: "当前进度较低，建议将目标分解为更小的任务，逐步完成。",
        });
      }

      if (confidence < 60) {
        this.learningSuggestions.push({
          id: 5,
          type: "tip",
          icon: "🤔",
          title: "信心提升建议",
          description: "学习信心较低，建议回顾已掌握的知识，增强自信心。",
        });
      }
    },

    // 开始复习（基于间隔重复理论）
    startReview(item) {
      if (item.status === "completed") {
        this.$message.info("该复习项目已完成");
        return;
      }

      this.$confirm(`开始复习：${item.content}？`, "确认复习", {
        confirmButtonText: "开始",
        cancelButtonText: "稍后",
        type: "info",
      })
        .then(() => {
          // 标记为进行中
          item.status = "in-progress";
          item.statusText = "进行中";

          this.$message.success("开始复习！");

          // 模拟复习完成
          setTimeout(() => {
            item.status = "completed";
            item.statusText = "已完成";
            this.$message.success("复习完成！");
          }, 3000);
        })
        .catch(() => {
          this.$message.info("已取消复习");
        });
    },

    // 记录元认知评估
    recordMetacognition(confidence, difficulty, focus) {
      this.metacognitionData = {
        confidence: confidence,
        difficulty: difficulty,
        focus: focus,
      };

      // 保存到本地存储
      localStorage.setItem(
        "metacognitionData",
        JSON.stringify(this.metacognitionData)
      );

      this.$message.success("学习评估已记录");
    },

    // 显示详细数据模态框
    showDetailModal(type) {
      this.detailModalType = type;
      this.showDetailModalVisible = true;
    },

    // 获取趋势样式类
    getTrendClass(type) {
      const trend = this.getTrendValue(type);
      if (trend > 0) return "trend-up";
      if (trend < 0) return "trend-down";
      return "trend-same";
    },

    // 获取趋势文本
    getTrendText(type) {
      const trend = this.getTrendValue(type);
      if (trend > 0) return `+${trend}%`;
      if (trend < 0) return `${trend}%`;
      return "持平";
    },

    // 计算趋势值
    getTrendValue(type) {
      const today = this.todayStats;
      const yesterday = this.yesterdayStats;

      switch (type) {
        case "time": {
          const todayTime = parseInt(today.studyTime) || 0;
          const yesterdayTime = parseInt(yesterday.studyTime) || 0;
          return yesterdayTime > 0
            ? Math.round(((todayTime - yesterdayTime) / yesterdayTime) * 100)
            : 0;
        }

        case "tasks":
          return yesterday.completedTasks > 0
            ? Math.round(
                ((today.completedTasks - yesterday.completedTasks) /
                  yesterday.completedTasks) *
                  100
              )
            : 0;

        case "questions":
          return yesterday.questionsAnswered > 0
            ? Math.round(
                ((today.questionsAnswered - yesterday.questionsAnswered) /
                  yesterday.questionsAnswered) *
                  100
              )
            : 0;

        case "streak":
          return yesterday.streakDays > 0
            ? Math.round(
                ((today.streakDays - yesterday.streakDays) /
                  yesterday.streakDays) *
                  100
              )
            : 0;

        default:
          return 0;
      }
    },
  },
};
</script>

<style scoped>
/* 页面容器 */
.task-page {
  min-height: 100vh;
  background: #f8f9fa;
  position: relative;
  overflow-x: hidden;
}

/* 隐藏炫彩背景装饰，使风格更简洁，贴近学习页 */
.background-decoration {
  display: none;
}

.task-page::before {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #f8f9fa;
  z-index: -1;
}

/* 页面头部 */
.page-header {
  color: #2c3e50;
  padding: 60px 20px 40px;
  text-align: center;
  position: relative;
  overflow: hidden;
}

/* 动机卡片 */
.motivation-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  padding: 30px;
  margin: 30px auto 0;
  max-width: 600px;
  color: white;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
}

.motivation-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.motivation-icon {
  font-size: 3rem;
  flex-shrink: 0;
}

.motivation-text h3 {
  font-size: 1.5rem;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.motivation-text p {
  font-size: 1.1rem;
  margin: 0;
  opacity: 0.9;
}

.header-content {
  position: relative;
  z-index: 1;
  max-width: 800px;
  margin: 0 auto;
}

/* 头部标题与副标题样式，参考学习页 */
.page-title {
  font-size: 3rem;
  font-weight: 700;
  margin: 0 0 20px 0;
  color: #2c3e50;
}

.page-subtitle {
  font-size: 1.3rem;
  margin: 0;
  color: #6c757d;
}

/* 主要内容区域 */
.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 40px;
  position: relative;
  z-index: 1;
  background: transparent;
}

/* 统一卡片风格为白底+浅灰边，弱化玻璃拟态效果 */
.glass-card {
  background: #ffffff !important;
  border: 1px solid #e9ecef !important;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.05) !important;
  border-radius: 12px !important;
}

/* 目标设定区域 */
.goals-section {
  margin-bottom: 30px;
}

.goals-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  margin-top: 20px;
}

.goal-setting-card,
.goal-progress-card {
  background: white;
  border-radius: 15px;
  padding: 25px;
  border: 1px solid #e9ecef;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.goal-setting-card h3,
.goal-progress-card h3 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin: 0 0 20px 0;
  font-weight: 600;
}

.goal-input-group {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.goal-input {
  width: 80px;
  padding: 10px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 1.1rem;
  text-align: center;
  transition: border-color 0.3s ease;
}

.goal-input:focus {
  outline: none;
  border-color: #667eea;
}

.goal-unit {
  font-size: 1rem;
  color: #6c757d;
  font-weight: 500;
}

.set-goal-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 10px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.set-goal-btn:hover {
  transform: translateY(-2px);
}

/* 进度圆环 */
.progress-circle {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.progress-ring {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: conic-gradient(#667eea var(--progress, 0%), #e9ecef 0);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.progress-ring::before {
  content: "";
  position: absolute;
  width: 80px;
  height: 80px;
  background: white;
  border-radius: 50%;
}

.progress-text {
  position: relative;
  z-index: 1;
  font-size: 1.5rem;
  font-weight: 700;
  color: #2c3e50;
}

.goal-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 0.9rem;
  color: #6c757d;
  margin-bottom: 5px;
}

.stat-value {
  display: block;
  font-size: 1.2rem;
  font-weight: 600;
  color: #2c3e50;
}

/* 科学学习功能 */
.science-learning-section {
  margin-bottom: 30px;
}

.science-features {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.feature-card {
  background: white;
  border-radius: 15px;
  padding: 25px;
  border: 1px solid #e9ecef;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-5px);
}

.feature-icon {
  font-size: 2.5rem;
  margin-bottom: 15px;
}

.feature-content h4 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.feature-content p {
  color: #6c757d;
  margin: 0 0 20px 0;
  line-height: 1.5;
}

/* 复习计划 */
.review-schedule {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.schedule-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.schedule-item:hover {
  background: #e9ecef;
}

.schedule-time {
  font-weight: 600;
  color: #667eea;
  min-width: 50px;
}

.schedule-content {
  flex: 1;
  color: #2c3e50;
}

.schedule-status {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.schedule-status.pending {
  background: #fff3cd;
  color: #856404;
}

.schedule-status.completed {
  background: #d4edda;
  color: #155724;
}

.schedule-status.in-progress {
  background: #cce5ff;
  color: #004085;
}

/* 检索练习统计 */
.retrieval-stats {
  display: flex;
  justify-content: space-around;
}

.retrieval-item {
  text-align: center;
}

.retrieval-label {
  display: block;
  font-size: 0.9rem;
  color: #6c757d;
  margin-bottom: 5px;
}

.retrieval-value {
  display: block;
  font-size: 1.5rem;
  font-weight: 700;
  color: #667eea;
}

/* 元认知图表 */
.metacognition-chart {
  margin-top: 15px;
}

.confidence-level {
  display: flex;
  align-items: center;
  gap: 15px;
}

.confidence-label {
  font-size: 0.9rem;
  color: #6c757d;
  min-width: 80px;
}

.confidence-bar {
  flex: 1;
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  overflow: hidden;
}

.confidence-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transition: width 0.3s ease;
}

.confidence-value {
  font-size: 0.9rem;
  font-weight: 600;
  color: #2c3e50;
  min-width: 40px;
}

/* 概览区域 */
.overview-section {
  margin-bottom: 30px;
}

/* 统计卡片优化 */
.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.4),
    transparent
  );
  transition: left 0.5s ease;
}

.stat-card:hover::before {
  left: 100%;
}

/* 趋势指示器 */
.stat-trend {
  font-size: 0.8rem;
  font-weight: 600;
  margin-top: 5px;
  padding: 2px 6px;
  border-radius: 10px;
  display: inline-block;
}

.trend-up {
  color: #10b981;
  background: rgba(16, 185, 129, 0.1);
}

.trend-down {
  color: #ef4444;
  background: rgba(239, 68, 68, 0.1);
}

.trend-same {
  color: #6b7280;
  background: rgba(107, 114, 128, 0.1);
}

/* 进度提示 */
.progress-tips {
  margin-top: 15px;
  text-align: center;
}

.tip-text {
  font-size: 0.9rem;
  color: #6b7280;
  font-style: italic;
  padding: 8px 15px;
  background: rgba(107, 114, 128, 0.05);
  border-radius: 15px;
  display: inline-block;
}

.progress-section {
  margin-top: 30px;
}

.progress-title {
  font-size: 1.2rem;
  color: #2c3e50;
  margin-bottom: 15px;
  font-weight: 600;
}

.progress-bar {
  height: 12px;
  background: #e9ecef;
  border-radius: 6px;
}

.progress-fill {
  background: #6c757d;
}

/* 统一按钮体系为中性灰与蓝灰系 */
.primary-btn,
.secondary-btn {
  padding: 12px 25px;
  border-radius: 25px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  border: 1px solid #e9ecef;
}

.primary-btn {
  background: #6c757d;
  color: #fff;
}

.primary-btn:hover {
  background: #5a6268;
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(108, 117, 125, 0.2);
}

.secondary-btn {
  background: #ffffff;
  color: #6c757d;
}

.secondary-btn:hover {
  background: #f1f3f5;
  color: #343a40;
  transform: translateY(-2px);
}

/* 任务区域 */
.tasks-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.add-task-btn {
  padding: 10px 20px;
  background: #6c757d;
  color: #fff;
  border: none;
  border-radius: 20px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.add-task-btn:hover {
  background: #5a6268;
  transform: translateY(-2px);
}

.tasks-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.task-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  border: 2px solid #e1e5e9;
  transition: all 0.3s ease;
}

.task-item:hover {
  border-color: #6c757d;
  box-shadow: 0 4px 12px rgba(108, 117, 125, 0.12);
}

.task-item.completed {
  background: #f8f9fa;
  border-color: #ced4da;
}

.task-item.completed .task-title {
  text-decoration: line-through;
  color: #6c757d;
}

.task-checkbox {
  margin-top: 5px;
}

.task-checkbox-input {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.task-content {
  flex: 1;
}

.task-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.task-description {
  color: #6c757d;
  margin: 0 0 10px 0;
  line-height: 1.5;
}

.task-meta {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.task-type,
.task-duration,
.task-priority {
  font-size: 0.85rem;
  padding: 4px 8px;
  border-radius: 12px;
  font-weight: 500;
}

.task-type {
  background: #f1f3f5;
  color: #6c757d;
}

.task-duration {
  background: #f8f9fa;
  color: #6c757d;
}

.task-priority {
  background: #f8f9fa;
  color: #6c757d;
}

.task-priority.priority-high {
  background: #f1f3f5;
  color: #495057;
}

.task-priority.priority-medium {
  background: #f8f9fa;
  color: #6c757d;
}

.task-priority.priority-low {
  background: #ffffff;
  color: #6c757d;
  border: 1px solid #e9ecef;
}

.task-actions {
  display: flex;
  gap: 8px;
}

.task-action-btn {
  width: 35px;
  height: 35px;
  border: 1px solid #e9ecef;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-btn,
.delete-btn {
  background: #ffffff;
  color: #6c757d;
}

.edit-btn:hover,
.delete-btn:hover {
  background: #f1f3f5;
  color: #343a40;
}

.empty-tasks {
  text-align: center;
  padding: 60px 20px;
  color: #6c757d;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 20px;
}

.empty-tasks h3 {
  font-size: 1.5rem;
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.empty-tasks p {
  margin: 0;
  font-size: 1.1rem;
}

/* 习惯分析区域 */
.habits-section {
  margin-bottom: 30px;
}

.habits-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.habit-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  border: 1px solid #e1e5e9;
  transition: all 0.3s ease;
}

.habit-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.habit-icon {
  font-size: 2rem;
  flex-shrink: 0;
}

.habit-content {
  flex: 1;
}

.habit-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.habit-desc {
  color: #6c757d;
  margin: 0 0 10px 0;
}

.habit-progress {
  margin-top: 10px;
}

.achievement-badges {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.badge {
  font-size: 0.8rem;
  padding: 4px 8px;
  background: #f1f3f5;
  color: #6c757d;
  border-radius: 12px;
  font-weight: 500;
}

/* 建议区域 */
.suggestions-section {
  margin-bottom: 30px;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 20px;
  border-radius: 12px;
  border-left: 4px solid;
}

.suggestion-tip {
  background: #f8f9fa;
  border-left-color: #ced4da;
}

.suggestion-warning {
  background: #f8f9fa;
  border-left-color: #ced4da;
}

.suggestion-success {
  background: #f8f9fa;
  border-left-color: #ced4da;
}

.suggestion-icon {
  font-size: 1.5rem;
  flex-shrink: 0;
  color: #6c757d;
}

.suggestion-content {
  flex: 1;
}

.suggestion-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.suggestion-desc {
  color: #6c757d;
  margin: 0;
  line-height: 1.5;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 15px;
  max-width: 500px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #e1e5e9;
}

.modal-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.modal-close {
  width: 30px;
  height: 30px;
  border: none;
  background: #f8f9fa;
  border-radius: 50%;
  font-size: 1.2rem;
  color: #6c757d;
  cursor: pointer;
  transition: all 0.3s ease;
}

.modal-close:hover {
  background: #e9ecef;
  color: #333;
}

.modal-body {
  padding: 25px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 20px 25px;
  border-top: 1px solid #e1e5e9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 0 15px 30px;
  }

  .page-header {
    padding: 40px 15px 30px;
  }

  .motivation-card {
    margin: 20px 15px 0;
    padding: 20px;
  }

  .motivation-content {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }

  .motivation-icon {
    font-size: 2.5rem;
  }

  .goals-container {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .science-features {
    grid-template-columns: 1fr;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .habits-grid {
    grid-template-columns: 1fr;
  }

  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .task-item {
    flex-direction: column;
    gap: 10px;
  }

  .task-actions {
    align-self: flex-end;
  }

  .modal-content {
    margin: 10px;
  }

  .progress-ring {
    width: 100px;
    height: 100px;
  }

  .progress-ring::before {
    width: 70px;
    height: 70px;
  }

  .progress-text {
    font-size: 1.2rem;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
